//=============================================================================
// The main application. Uses the Luna DirectX10 framework.
//
//=============================================================================
#include <d3dApp.h>
#include <d3dUtil.h>
#include <Utils\Globals.h>
#include <Utils\KeyboardHandler.h>

#include <VxlObjects\VxlObject.h>
#include <VxlObjects\Blueprints\Numbers.h>
#include <VxlEngine.h>

#ifdef _DEBUG
#ifdef MEMORY_LEAK_CHECK
//#include "vld/vld.h"
#endif		
#endif

using namespace Drawables;

class Sandbox : public D3DApp
{
public:
	Sandbox(HINSTANCE hInstance);
	~Sandbox();

	void initApp();
	void onResize();
	void updateScene(float dt);
	void drawScene(); 
	void CleanApp();

private:
	VxlEngine VxlEngine;
};

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
	PSTR cmdLine, int showCmd)
{
	Sandbox theApp(hInstance);

	theApp.initApp();

	if(!Globals::CORRECTLY_SETUP)
		PostQuitMessage(0);

	return theApp.run();
}

Sandbox::Sandbox(HINSTANCE hInstance)
	: D3DApp(hInstance, "Vxl Engine Sandbox") 
{	

} 

Sandbox::~Sandbox()
{
	if( md3dDevice )
		m_deviceContext->ClearState();
}

void Sandbox::CleanApp(){
	
}

void Sandbox::initApp()
{
	D3DApp::initApp();
	VxlEngine = VxlEngine::VxlEngine(this->md3dDevice, this->mhMainWnd, this->mhAppInst, true, true);
	
	Drawables::VxlObject* VxlObject = new Drawables::VxlObject();	

	//VxlObject->CreateFromBlueprint(Blueprints::One(), XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f));
	VxlObject->AddVxl(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f));
	
	VxlObject->Initialize();
	VxlEngine.AddVxl(VxlObject);
	
}

void Sandbox::onResize()
{
	D3DApp::onResize();
	Globals::Device = md3dDevice;
}

void Sandbox::updateScene(float dt)
{
	if(this->mAppPaused || dt > 0.5f)
		return;

	if(Utils::KeyboardHandler::IsKeyDown(DIK_ESCAPE)){
		CleanApp();
		PostQuitMessage(0);
	}
	
	D3DApp::updateScene(dt);
	VxlEngine.Update(dt);
}

void Sandbox::drawScene()
{
	if(this->mAppPaused)
		return;
	
	D3DApp::drawScene();	

	VxlEngine.Draw(0.0f);
	HRESULT hr = mSwapChain->Present(1, 0);

	if(FAILED(hr)){
		CleanApp();
		PostQuitMessage(0);
	}	
}
